package gate

import (
	"errors"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"iot-base/auth/api/logic/gatelogic"
	"iot-base/auth/svc"
	"iot-base/auth/types"
)

func Add(c *gin.Context) {
	resp := types.NewResult(c)
	var req types.ReqAddGate

	err := c.ShouldBind(&req)
	if err != nil {
		resp.ErrorCode(types.ParamsError, "")
		return
	}
	var logic gatelogic.BaseGate
	logic = gatelogic.NewGate()
	err = logic.AddPeople(req)
	if err != nil {
		resp.ErrorCode(types.Fail, err.Error())
		return
	}
	resp.Success(gin.H{})
	return
}

func Modify(c *gin.Context) {
	resp := types.NewResult(c)
	var req types.ReqModifyGate

	err := c.ShouldBind(&req)
	if err != nil {
		resp.ErrorCode(types.ParamsError, err.Error())
		return
	}
	var logic gatelogic.BaseGate
	logic = gatelogic.NewGate()
	err = logic.ModifyPeople(req)
	if err != nil {
		resp.ErrorCode(types.Fail, err.Error())
		return
	}
	resp.Success(gin.H{})
	return
}

func Delete(c *gin.Context) {
	resp := types.NewResult(c)
	var req types.ReqDelGate

	err := c.ShouldBind(&req)
	if err != nil {
		resp.ErrorCode(types.ParamsError, "")
		return
	}
	var logic gatelogic.BaseGate
	logic = gatelogic.NewGate()
	err = logic.RemovePeople(req)
	if err != nil {
		resp.ErrorCode(types.Fail, err.Error())
		return
	}
	resp.Success(gin.H{})
	return
}

func SelectList(c *gin.Context) {

	resp := types.NewResult(c)
	var req types.ReqQueryGateList

	err := c.ShouldBind(&req)
	if err != nil {
		resp.ErrorCode(types.ParamsError, "")
		return
	}

	sql := "SELECT t2.thing_id,t.s_name as thing_name FROM things t INNER JOIN thing_stations t2 on t.uid = t2.thing_id where t2.station_id = ? and  t2.model_id=?;"
	var data []map[string]interface{}
	err = svc.Dao.GetDb().Raw(sql, req.StationId, "m_Door").Find(&data).Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		resp.Success(gin.H{"list": data})
		return
	}

	if err != nil {
		resp.ErrorCode(types.Fail, err.Error())
		return
	}
	resp.Success(gin.H{"list": data})
	return
}

func UserGate(c *gin.Context) {
	resp := types.NewResult(c)
	var req types.ReqUserGateList

	err := c.ShouldBind(&req)
	if err != nil || (req.UserId == 0 && req.ThingId == "") {
		resp.ErrorCode(types.ParamsError, err.Error())
		return
	}

	if err != nil {
		resp.ErrorCode(types.Fail, err.Error())
		return
	}
	total, result, err := gatelogic.NewGateLogic().GetUserGateList(req)
	if err != nil {
		resp.ErrorCode(types.Fail, err.Error())
		return
	}
	resp.Success(gin.H{"total": total, "list": result})
	return
}
